package com.example.yan_music.view;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.example.yan_music.R;
import com.example.yan_music.adapter.MainViewPagerAdapter;
import com.example.yan_music.base.activity.BaseActivity;
import com.example.yan_music.event.PlayCompleteEvent;
import com.example.yan_music.event.PlayDurationEvent;
import com.example.yan_music.event.PlayErrorEvent;
import com.example.yan_music.event.PlayerInfoEvent;
import com.example.yan_music.event.SetThreadInterrupt;
import com.example.yan_music.event.SongCoverUriEvent;
import com.example.yan_music.event.SongIsPreparedEvent;
import com.example.yan_music.event.ReplaceViewPagerFragmentEvent;
import com.example.yan_music.service.PlayerService;
import com.example.yan_music.utils.DipAndPxUtils;
import com.example.yan_music.utils.XLog;
import com.example.yan_music.utils.XToast;
import com.example.yan_music.view.fragment.MyFragment;
import com.example.yan_music.view.fragment.SearchFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 主活动
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private static final String TAG = "MainActivity";

    /**
     * 连续点击相关设置
     */
    private static final int CLICK_COUNT = 3; //连续点击的次数
    private static long DURATION = 1500; // 完成连续点击持续的时间
    private long[] mClickArray = new long[CLICK_COUNT]; // 保存点击时间的数组

    /**
     * 布局
     */
    private LinearLayout ll_main_player;
    private DrawerLayout dl_sides_lip;


    /**
     * 播放服务
     */
    private PlayerService.PlayBinder mPlayBinder;
    private ServiceConnection connection;

    /**
     * 播放视图、SeekBar相关参数
     */
    private RelativeLayout mRlPlayer;   // 整个player视图
    private CircleImageView mCivSongCover; // 歌曲封面
    private TextView mTvSongName, // 歌曲名
            mTvTab1,   // Music按钮
            mTvMy;      // My按钮
    private ImageView mImagTab1, mImgMy;

    private SeekBar mPlaySeekBar;   // 播放进度条
    private int mCurrentPlayPosition; // 当前播放位置
    private boolean isPause = false; // 是否暂停
    private boolean isDrag = false; // 是否拖动
    private boolean isInterrupt = false; // 是否中断线程
    private Thread mSeekBarThread; // SeekBar更新线程

    /**
     * ViewPager相关
     */
    private ViewPager mViewPager;
    private List<Fragment> mFragmentList = new ArrayList<>(); // viewpager搭载的Fragment集合
    private MainViewPagerAdapter mViewPagerAdapter;
    private boolean isMusicChecked = true;
    private boolean isMyChecked = false;

    /**
     * 弧形菜单
     */
    private CircleImageView mMenu1, mMenu2, mMenu3;
    private boolean isMenuOpened = false;

    /**
     * 封面动画
     */
    private ObjectAnimator mCoverAnimation;

    /**
     * player隐藏显示相关
     */
    private boolean isAnimate;  // isAnimate表示需要显示/隐藏的时候才会去调用hide/show,而不是一直滑动一直调用hide/show

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 修改状态栏
        modifyStatusBar(true, R.color.statusBarColor_main_white);
        modifyNavigationBar(R.color.baise);
        initView();
        initBase();
        initViewPager();
        initCoverAnimation();
        Log.d(TAG, "onCreate: " + DipAndPxUtils.px2dip(this, 2240));
    }

    /**
     * 基础配置
     */
    private void initBase() {
        // 订阅事件
        EventBus.getDefault().register(this);
        // 绑定播放服务
        bingPlayService();
        initCoverAnimation();
        setCoverMenu();
    }

    /**
     * 配置封面动画
     */
    private void initCoverAnimation() {
        mCoverAnimation = ObjectAnimator.ofFloat(mCivSongCover, "rotation", 0, 360);
        mCoverAnimation.setDuration(25000);
        mCoverAnimation.setInterpolator(new LinearInterpolator());
        mCoverAnimation.setRepeatMode(ValueAnimator.RESTART);
        mCoverAnimation.setRepeatCount(ValueAnimator.INFINITE);
    }

    /**
     * 绑定播放服务
     */
    private void bingPlayService() {
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mPlayBinder = (PlayerService.PlayBinder) service;
                XLog.d(name + " 播放服务启动");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mPlayBinder = null;
            }
        };
        Intent playIntent = new Intent(this, PlayerService.class);
        bindService(playIntent, connection, Context.BIND_AUTO_CREATE);
    }

    private void initView() {
        //ll_main_player = findViewById(R.id.ll_main_player);
        dl_sides_lip = findViewById(R.id.dl_sideslip_layout);

        //tv_song_name = findViewById(R.id.tv_song_name);
        //tv_singer_name = findViewById(R.id.tv_singer);
        //img_play_or_pause = findViewById(R.id.img_play_pause_or_start);
        //img_next = findViewById(R.id.img_play_next);
        //img_previous = findViewById(R.id.img_play_ever);
        //civ_cover = findViewById(R.id.img_song_cover);
        mPlaySeekBar = findViewById(R.id.seekbar);
        //tv_duration = findViewById(R.id.duration);

        mViewPager = findViewById(R.id.vp_fragment_container);

        mRlPlayer = findViewById(R.id.rl_main_player);
        mCivSongCover = findViewById(R.id.civ_song_cover);
        mTvSongName = findViewById(R.id.tv_player_song_name);
        mTvTab1 = findViewById(R.id.tv_music);
        mTvMy = findViewById(R.id.tv_my);
        mImagTab1 = findViewById(R.id.img_main_music);
        mImgMy = findViewById(R.id.img_mian_my);

        //img_play_or_pause.setOnClickListener(this);
        //img_next.setOnClickListener(this);
        //img_previous.setOnClickListener(this);
        mPlaySeekBar.setOnSeekBarChangeListener(this);
        mImagTab1.setOnClickListener(this);
        mImgMy.setOnClickListener(this);

        mMenu1 = findViewById(R.id.civ_menu_1);
        mMenu2 = findViewById(R.id.civ_menu_2);
        mMenu3 = findViewById(R.id.civ_menu_3);

    }

    /**
     * 设置player视图上面的信息
     *
     * @param songName
     * @param singerName
     */
    public void setPlayerInfo(String songName, String singerName) {
        // 更改View的选择状态，不设置true的话Tv文字不能滚动（跑马灯效果）
        mTvSongName.setSelected(true);
        mTvSongName.setText(songName);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解绑播放服务
        unbindService(connection);
        // 取消EventBus的订阅
        EventBus.getDefault().unregister(this);
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_play_pause_or_start:
                if (mPlayBinder.isPlaying()) {
                    // 记录当前暂停的位置
                    mCurrentPlayPosition = mPlayBinder.getCurrentPosition();
                    // 中断线程
                    isInterrupt = true;
                    // 设置暂停标志为true
                    isPause = true;
                    // 将播放状态设置为false，也就是未播放
                    mPlayBinder.setPlaying(false);
                    // 将歌曲暂停
                    mPlayBinder.pause();
                    Log.d(TAG, "onClick: =================== 歌曲暂停了");
                    // 将图标设置为暂停图标
                    //img_play_or_pause.setImageResource(R.drawable.bofang_1);
                    break;
                }
                if (isPause) {
                    isPause = false;
                    mPlayBinder.setPlaying(true);
                    isInterrupt = false;
                    Log.d(TAG, "onClick: =================== 歌曲开始播放");
                    // 从暂停的位置开始播放
                    mPlayBinder.seekTo(mCurrentPlayPosition);
                    mPlayBinder.play();
                    //img_play_or_pause.setImageResource(R.drawable.zanting_1);
                    mSeekBarThread = new Thread(new SeekBarUpdateThread());
                    mSeekBarThread.start();
                    break;
                }
            case R.id.img_play_next:
                //XToast.show("下一首", XToast.Type.POINT);
                break;
            case R.id.img_play_ever:
                XToast.show("上一首", XToast.Type.POINT);
                break;
            case R.id.img_main_music:
                // Music被选中，viewpager滑到对应的位置
                changeTabOneSelected();
                mViewPager.setCurrentItem(0);
                isCoverMenuOpen();
                break;
            case R.id.img_mian_my:
                mViewPager.setCurrentItem(1);
                // 根据0位置上是什么Fragment设置对应的图标和文字
                changeTabMySelected();
                isCoverMenuOpen();
            default:
                break;
        }
    }

    /**
     * 菜单如果是打开的话，就关闭
     */
    public void isCoverMenuOpen() {
        if (isMenuOpened) {
            closeCoverMenu();
        }
    }

    /**
     * 设置歌曲封面
     *
     * @param songCoverUriEvent SongCoverUri事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setSongCover(SongCoverUriEvent songCoverUriEvent) {
        Glide.with(this)
                .load(songCoverUriEvent.getCoverUri())
                //.placeholder(R.drawable.pre_cover)
                .into(mCivSongCover);
    }

    /**
     * 设置底部Player文本信息
     *
     * @param playerInfoEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setPlayer(PlayerInfoEvent playerInfoEvent) {
        setPlayerInfo(playerInfoEvent.getSongName(), playerInfoEvent.getSingerName());
    }

    /**
     * 设置Player的最大进度
     *
     * @param playDurationEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setSeekBarMax(PlayDurationEvent playDurationEvent) {
        int seekBarMax = playDurationEvent.getDuration();
        if (playDurationEvent.isPaidSong()) {
            // 设置付费歌曲试听时长为max
            mPlaySeekBar.setMax(seekBarMax);
            String songTime = changeTime(seekBarMax);
            //tv_duration.setText(songTime);
        } else {
            // 设置非付费歌曲完整时长为max
            mPlaySeekBar.setMax(seekBarMax);
            String songTime = changeTime(playDurationEvent.getDuration());
            //tv_duration.setText(songTime);
        }
        XLog.d("执行流程1：设置SeekBar最大值为 = " + seekBarMax);
    }

    /**
     * 播放错误
     *
     * @param errorEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void playError(PlayErrorEvent errorEvent) {
        isInterrupt = true;
        mPlaySeekBar.setProgress(0);
        //img_play_or_pause.setImageResource(R.drawable.bofang_1);
    }

    /**
     * 当歌曲准备完成后启动SeekBarThread
     *
     * @param songIsPreparedEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void startSeekBarThread(SongIsPreparedEvent songIsPreparedEvent) {
        Log.d(TAG, "startSeekBarThread: " + mPlayBinder.isPlaying());
        mPlaySeekBar.setProgress(0);
        // 开始封面动画
        startCoverAnim();
        mSeekBarThread = new Thread(new SeekBarUpdateThread());
        mSeekBarThread.start();
    }

    /**
     * 歌曲播放结束后将SeekBar进度设为0
     *
     * @param playCompleteEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void revertSeekBarAfterPlayCompletion(PlayCompleteEvent playCompleteEvent) {
        // 将进度设置为0
        mPlaySeekBar.setProgress(0);
        // 中断线程
        isInterrupt = true;
        // 取消封面动画
        cancelCoverAnim();
        Log.d(TAG, "revertSeekBarAfterPlayCompletion: " + "被调用");
    }

    /**
     * 当点击某个子项要播放歌曲的时候调用
     * 将SeekBar线程中断标志设为false，保证可以更新SeekBar
     *
     * @param setThreadInterrupt
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setIsInterrupt(SetThreadInterrupt setThreadInterrupt) {
        isInterrupt = setThreadInterrupt.isInterrupt();
        Log.d(TAG, "setIsInterrupt: " + isInterrupt);
    }

    /**
     * 处理切换Fragment
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void replaceFragmentInViewPager(ReplaceViewPagerFragmentEvent event) {
        mFragmentList.set(0, event.getFragment());
        mViewPagerAdapter.setReplace(true);
        mViewPagerAdapter.notifyDataSetChanged();
    }

    /**
     * 通知进度已经被修改
     *
     * @param seekBar  当前被修改的SeekBar
     * @param progress 当前的进度值，区间：[0, max]
     * @param fromUser 用来区分是否是用户触发还是代码触发
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // Log.d(TAG, "onProgressChanged: 是否由用户操作引起：" + fromUser + "      当前播放进度：" + progress);
    }

    /**
     * 通知用户已经开始一个触摸拖动手势
     *
     * @param seekBar 触摸的SeekBar
     */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // 当拖动时，可能会与更新冲突，将isDrag设为true,这样就不会更新了
        isDrag = true;
    }

    /**
     * 通知用户触摸手势已经结束
     *
     * @param seekBar 触摸的SeekBar
     */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // 当用户结束拖动时，从结束位置播放
        Log.d(TAG, "onStopTrackingTouch: " + "===================== SeekBar拖动结束");
        // 拖动结束时的进度
        int currentProgress = mPlaySeekBar.getProgress();
        // 在当前进度位置播放
        mPlayBinder.seekTo(currentProgress);
        // 将isDrag设为false，满足SeekBarThread线程更新条件
        isDrag = false;
        // 开启线程
        isInterrupt = false;
        mSeekBarThread = new Thread(new SeekBarUpdateThread());
        mSeekBarThread.start();
    }

    /**
     * 时间转换方法
     * 1200ms --> 00:12
     *
     * @param time
     * @return
     */
    public String changeTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    /**
     * 执行连续点击事件
     */
    public void executeContinuousClickEvent() {
        // 每次点击让数组前进一位
        System.arraycopy(mClickArray, 1, mClickArray, 0, mClickArray.length - 1);
        // 为数组的最后一个位置赋值（SystemClock.uptimeMillis()表示系统开机到现在的时间总数，单位是ms）
        mClickArray[mClickArray.length - 1] = SystemClock.uptimeMillis();
        /** 当用户完成3次点击时，判断一下完成三次点击使用的时间是否在DURATION范围之内
         click1   click2        click3
         ↓      ↓              ↓
         -------|------------------------------|----------> 时间轴(SystemClock.uptimeMills())
         |<—————————— DURATION ————————>|
         */
        if (mClickArray[0] >= SystemClock.uptimeMillis() - DURATION) {
            // 完成连续点击事件后初始化数组
            mClickArray = new long[CLICK_COUNT];
            XToast.showError("连续点击");
        }
    }

    /**
     * 处理Fragment返回键事件和MainActivity的返回键事件
     */
    @Override
    public void onBackPressed() {
        List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
        for (Fragment fragment : fragmentList) {
            // 点击返回键 <
            // Activity : onBackPressed 执行
            //              ↓
            // 如果点击返回键的Fragment是自定义的BaseFragment的子类时
            //              ↓
            // 如果这个子类Fragment中重写了onBackPressed方法（没有重写的话就直接返回false了）
            //              ↓
            // 子类重写的onBackPressed中返回的是true的话就交给自身处理，否则就是交给Activity处理,这样就达到了拦截效果
            if (fragment instanceof com.example.yan_music.base.fragment.BaseFragment) {
                if (((com.example.yan_music.base.fragment.BaseFragment) fragment).onBackPressed()) {
                    return;
                }
            }
        }
        super.onBackPressed();
    }

    /**
     * 配置ViewPager
     */
    private void initViewPager() {
        mFragmentList.add(new MainFragment()); // 0
        mFragmentList.add(new MyFragment());    // 1
        mViewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mFragmentList);
        mViewPager.setAdapter(mViewPagerAdapter);
        // 解决MainActivity多次滑动闪退，启动ViewPager预加载
        mViewPager.setOffscreenPageLimit(mFragmentList.size());
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d(TAG, "onPageScrolled: " + "\nposition = " + position + "\npositionOffset = " + positionOffset + "\npositionOffsetPixels = " + positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                Log.d(TAG, "onPageSelected: " + "ViewPager当前位置 = " + position);
                switch (position) {
                    case 0:
                        isMusicChecked = true;
                        changeTabOneSelected();
                        isCoverMenuOpen();
                        break;
                    case 1:
                        isMyChecked = true;
                        changeTabMySelected();
                        isCoverMenuOpen();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // 0:滑动结束， 1： 正在滑动， 2：调整滑动
                Log.d(TAG, "onPageScrollStateChanged: " + "viewpager正在滑动，滑动状态为" + state);
                // 如果左右滑动过程中Player是隐藏状态的话，让它显示
                isCoverMenuOpen();
            }
        });
    }

    /**
     * "My"被选中
     */
    private void changeTabMySelected() {
        modifyPlayerTabTwoIconAndText(R.drawable.mian_my_select, "My",R.color.player_text_color);
        // tab 1 要根据具体是什么Fragment去设置
        if(mViewPagerAdapter.getItem(0) instanceof MainFragment){
           modifyPlayrTabOneIconAndText(R.drawable.new_music_icon_unselect, "Music", R.color.player_text_unselect_color);
        }else if(mViewPagerAdapter.getItem(0) instanceof SearchFragment){
            modifyPlayrTabOneIconAndText(R.drawable.tab_1_search_off, "搜索", R.color.player_text_unselect_color);
        }else {

        }
    }

    /**
     * 修改player中 tab 2的图标文字
     * 
     * @param imgResId      图标资源ID
     * @param textColorId   文本颜色
     */
    private void modifyPlayerTabTwoIconAndText(int imgResId, String tip,int textColorId) {
        mImgMy.setBackgroundResource(imgResId);
        mTvMy.setTextColor(getColor(textColorId));
        mTvMy.setText(tip);
    }

    /**
     * player 第一个tab被选中
     */
    private void changeTabOneSelected() {
        mImgMy.setBackgroundResource(R.drawable.mian_my_unselect);
        mTvMy.setTextColor(getColor(R.color.player_text_unselect_color));
        if(mViewPagerAdapter.getItem(0) instanceof MainFragment){
            mImagTab1.setBackgroundResource(R.drawable.new_music_icon_select);
            mTvTab1.setTextColor(getColor(R.color.player_text_color1));
        }else if(mViewPagerAdapter.getItem(0) instanceof SearchFragment){
            mImagTab1.setBackgroundResource(R.drawable.tab_1_search_on);
            mTvTab1.setTextColor(getColor(R.color.tab1_on_color));
        }else {

        }
    }

    private void startCoverAnim() {
        mCoverAnimation.start();
    }

    private void cancelCoverAnim() {
        mCoverAnimation.cancel();
    }

    /**
     * 设置封面环形菜单
     */
    private void setCoverMenu() {
        mCivSongCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: " + isMenuOpened);
                if (!isMenuOpened) {
                    openCoverMenu();
                } else {
                    closeCoverMenu();
                }
            }
        });
        // 菜单的点击事件
        onCoverMenuItemClick();
    }

    /**
     * 关闭封面菜单
     */
    private void closeCoverMenu() {
        doCircleMenuClose(mMenu1, 1);
        doCircleMenuClose(mMenu2, 2);
        doCircleMenuClose(mMenu3, 3);
    }

    /**
     * 打开封面菜单
     */
    private void openCoverMenu() {
        doCircleMenuOpen(mMenu1, 1);
        doCircleMenuOpen(mMenu2, 2);
        doCircleMenuOpen(mMenu3, 3);
    }

    /**
     * 封面环形菜单打开动画
     *
     * @param view         要做动画的View
     * @param positionFlag 位置：从左到右分别是1,2,3
     */
    private void doCircleMenuOpen(View view, int positionFlag) {
        if (view.getVisibility() != View.VISIBLE) {
            view.setVisibility(View.VISIBLE);
        }
        isMenuOpened = true;
        // 45°对应的弧度值
        double radians = Math.toRadians(45);
        int translationX = (int) (Math.cos(radians) * 300);
        int translationY = (int) (Math.sin(radians) * 300);
        if (positionFlag == 1) {
            translationX = -translationX;
            translationY = -translationY;
        }
        if (positionFlag == 2) {
            translationX = 0;
            translationY = -300;
        }
        if (positionFlag == 3) {
            translationY = -translationY;
        }
        AnimatorSet aSet = new AnimatorSet();
        aSet.playTogether(
                ObjectAnimator.ofFloat(view, "translationX", 0, translationX),
                ObjectAnimator.ofFloat(view, "translationY", 0, translationY),
                ObjectAnimator.ofFloat(view, "alpha", 0f, 1),
                ObjectAnimator.ofFloat(view, "scaleX", 0f, 1),
                ObjectAnimator.ofFloat(view, "scaleY", 0f, 1)
        );
        aSet.setDuration(500).start();
    }

    /**
     * 封面环形菜单点击事件
     */
    private void onCoverMenuItemClick() {
        mMenu1.setOnClickListener(v -> {
            XToast.showInfo("点击了1");
            closeCoverMenu();
        });

        mMenu2.setOnClickListener(v -> {
            XToast.showInfo("点击了2");
            closeCoverMenu();
        });

        mMenu3.setOnClickListener(v -> {
            XToast.showInfo("点击了3");
            closeCoverMenu();
        });
    }

    /**
     * 封面环形菜单关闭动画
     *
     * @param view         要做动画的View
     * @param positionFlag 位置：从左到右分别是1,2,3
     */
    private void doCircleMenuClose(View view, int positionFlag) {
        if (view.getVisibility() != View.VISIBLE) {
            view.setVisibility(View.VISIBLE);
        }
        isMenuOpened = false;
        // 45°对应的弧度值
        double radians = Math.toRadians(45);
        int translationX = (int) (Math.cos(radians) * 300);
        int translationY = (int) (Math.sin(radians) * 300);
        if (positionFlag == 1) {
            translationX = -translationX;
            translationY = -translationY;
        }
        if (positionFlag == 2) {
            translationX = 0;
            translationY = -300;
        }
        if (positionFlag == 3) {
            translationY = -translationY;
        }
        AnimatorSet aSet = new AnimatorSet();
        aSet.playTogether(
                ObjectAnimator.ofFloat(view, "translationX", translationX, 0),
                ObjectAnimator.ofFloat(view, "translationY", translationY, 0),
                ObjectAnimator.ofFloat(view, "scaleX", 1f, 0),
                ObjectAnimator.ofFloat(view, "scaleY", 1f, 0),
                ObjectAnimator.ofFloat(view, "alpha", 1f, 0)
        );
        aSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        aSet.setDuration(500).start();
    }

    /**
     * 隐藏player视图
     * 动画：向下隐藏player布局
     *
     * @param view player布局
     */
    public void hidePlayer(View view) {
        // 创建一个属性动画，做translationY
        ViewPropertyAnimator animator = view.animate()
                // 平移到 y == viewY处
                .translationY(mRlPlayer.getHeight() + 100)
                .setInterpolator(new FastOutSlowInInterpolator())
                .setDuration(300);
        animator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isAnimate = true;
                isCoverMenuOpen();
                //Log.d(TAG, "hide onAnimationStart: " + "isAnimate = " + isAnimate);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAnimate = false;
                //view.setVisibility(View.INVISIBLE);
                Log.d(TAG, "hide onAnimationStart: " + "isAnimate = " + isAnimate);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                showPlayer(view);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }

    /**
     * 显示player视图
     * 动画：向上显示player
     *
     * @param view player布局
     */
    public void showPlayer(View view) {
        ViewPropertyAnimator animator = view.animate()
                // 平移到 y == 0处
                .translationY(0)
                .setInterpolator(new FastOutSlowInInterpolator())
                .setDuration(300);
        animator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isAnimate = true;
                isCoverMenuOpen();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAnimate = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                hidePlayer(view);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }

    /**
     * 修改Player上面的图标和标题
     *
     * @param imgResId    图标资源ID
     * @param tip         文本文字
     * @param textColorId 文本颜色值id
     */
    public void modifyPlayrTabOneIconAndText(int imgResId, String tip, int textColorId) {
        mImagTab1.setBackgroundResource(imgResId);
        mTvTab1.setText(tip);
        mTvTab1.setTextColor(getColor(textColorId));
    }

    /**
     * 获取isAnimate的值
     *
     * @return
     */
    public boolean isAnimate() {
        return isAnimate;
    }

    /**
     * 用于SeekBar更新的线程
     */
    private class SeekBarUpdateThread implements Runnable {
        @Override
        public void run() {
//            Log.d(TAG, "SeekBarThread更新线程[开启] ");
//            Log.d(TAG, "循环外: " + "isDrag = " + isDrag + ", isPlaying = " + mPlayBinder.isPlaying() + ", isInterrupt = " + isInterrupt);
            // 循环条件：当进度条没有被拖动且正在播放
            while (!isDrag && mPlayBinder.isPlaying() && !isInterrupt) {
                // 将SeekBar设置到当前播放位置
                mPlaySeekBar.setProgress((int) mPlayBinder.getCurrentPosition());
                // Log.d(TAG, "循环内: " + "isDrag = " + isDrag + ", isPlaying = " + mPlayBinder.isPlaying() + ", isInterrupt = " + isInterrupt);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}